package com.youmingxing.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.widget.EditText;

import com.youmingxing.activity.selfInfo.TopicActivity;
import com.youmingxing.utils.StringUtil;

/**
 *  EditText的长度和内容的监听
 */
public class TextLengthAndContentWatcher implements TextWatcher {
    private int length;
    private EditText editText;
    public static int REQUESTCODE_TOPIC = 1;
    private boolean onceLoad = true;
    private Activity mActivity;

    public TextLengthAndContentWatcher(Context context, int length, EditText editText) {
        mActivity = (Activity) context;
        this.length = length;
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int countSize = 0;
        Editable editable = editText.getText();
        String str = editable.toString();
        char[] array = str.toCharArray();
        if (onceLoad) {
            editText.setSelection(s.length());
            onceLoad = false;
        }
        for (int i = 0; i < array.length; i++) {
            if(array[0] == '#' && array.length == 1){
                System.out.println("输入#号了");
                Intent intent = new Intent(mActivity, TopicActivity.class);
                mActivity.startActivityForResult(intent,REQUESTCODE_TOPIC);
                return;
            }
            if (StringUtil.isChineseChar(str.charAt(i)))/**判断是否为中文*/
            {
                countSize += 2;/**如果为中文或者中文特殊符号则占两个字节*/
            } else {
                countSize += 1;/**英文则占一个字节*/
            }
            if (countSize > length) {
                /**达到最大值*/
                int selEndIndex = Selection.getSelectionEnd(editable);
                str = editable.toString();
                String newStr = str.substring(0, i);
                editText.setText(newStr);
                editable = editText.getText();
                int newLen = editable.length();
                if (selEndIndex > newLen) {
                    selEndIndex = editable.length();
                }
                Selection.setSelection(editable, selEndIndex);
                editText.setTextColor(Color.RED);
                break;
            } else {
                editText.setTextColor(Color.BLACK);
            }
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

}
